const puppeteer = require('puppeteer');
const path = require('path');
const fs = require('fs').promises;
const Article = require('../models/article');
const PublicAccount = require('../models/publicAccount');

class WeChatCrawler {
  constructor() {
    this.browser = null;
    this.page = null;
  }

  async init() {
    this.browser = await puppeteer.launch({
      headless: false,
      defaultViewport: null
    });
    this.page = await this.browser.newPage();
  }

  async login() {
    await this.page.goto('https://mp.weixin.qq.com/');
    
    // 保存登录二维码
    const qrCodeSelector = '.login__type__container__scan__qrcode img';
    await this.page.waitForSelector(qrCodeSelector);
    const qrCodeElement = await this.page.$(qrCodeSelector);
    
    const qrCodePath = process.env.QR_CODE_PATH;
    await fs.mkdir(path.dirname(qrCodePath), { recursive: true });
    await qrCodeElement.screenshot({ path: qrCodePath });
    
    // 等待登录成功
    await this.page.waitForNavigation({
      waitUntil: 'networkidle0',
      timeout: 300000 // 5分钟超时
    });
  }

  async crawlArticles(publicAccount) {
    try {
      // 访问公众号历史消息页面
      const historyUrl = `https://mp.weixin.qq.com/cgi-bin/appmsg?t=media/appmsg_list&action=list_ex&begin=0&count=10&fakeid=${publicAccount.biz}&type=9`;
      await this.page.goto(historyUrl);

      // 获取文章列表
      const articles = await this.page.evaluate(() => {
        const items = document.querySelectorAll('.weui-desktop-mass-appmsg__list .weui-desktop-mass-appmsg__item');
        return Array.from(items).map(item => ({
          title: item.querySelector('.weui-desktop-mass-appmsg__title').innerText.trim(),
          url: item.querySelector('a').href,
          publishDate: new Date(item.querySelector('.weui-desktop-mass-appmsg__time').innerText.trim())
        }));
      });

      // 保存文章
      for (const article of articles) {
        await this.page.goto(article.url);
        
        const content = await this.page.evaluate(() => {
          const contentElement = document.querySelector('#js_content');
          return contentElement ? contentElement.innerHTML : '';
        });

        const author = await this.page.evaluate(() => {
          const authorElement = document.querySelector('#js_name');
          return authorElement ? authorElement.innerText.trim() : '';
        });

        await Article.findOneAndUpdate(
          { url: article.url },
          {
            title: article.title,
            author,
            publicAccount: publicAccount.name,
            content,
            publishDate: article.publishDate,
            url: article.url
          },
          { upsert: true, new: true }
        );
      }

      // 更新公众号最后抓取时间
      await PublicAccount.findByIdAndUpdate(publicAccount._id, {
        lastCrawlTime: new Date()
      });

    } catch (error) {
      console.error(`抓取公众号 ${publicAccount.name} 文章失败:`, error);
    }
  }

  async crawlAllAccounts() {
    try {
      const accounts = await PublicAccount.find({ isActive: true });
      for (const account of accounts) {
        await this.crawlArticles(account);
      }
    } catch (error) {
      console.error('抓取所有公众号文章失败:', error);
    }
  }

  async close() {
    if (this.browser) {
      await this.browser.close();
    }
  }
}

module.exports = WeChatCrawler;